package com.bontroller.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class FileServerThread extends Thread {
	private FileBrowserServer server = null;
	private Socket socket = null;
	private int ID = -1;
	private DataInputStream streamIn = null;
	private DataOutputStream streamOut = null;

	public FileServerThread(FileBrowserServer _server, Socket _socket) {
		this.server = _server;
		this.socket = _socket;
		this.ID = this.socket.getPort();
	}

	public void send(String msg) {
		try {
			this.streamOut.writeUTF(msg);
			this.streamOut.flush();
		} catch (IOException ioe) {
			System.out.println(this.ID + " ERROR sending: " + ioe.getMessage());
			this.server.remove(this.ID);
			stop();
		}
	}

	public int getID() {
		return this.ID;
	}

	public void run() {
		System.out.println("Server Thread " + this.ID + " running.");
		while (true)
			try {
				this.server.handle(this.ID, this.streamIn.readUTF());
				continue;
			} catch (IOException ioe) {
				System.out.println(this.ID + " ERROR reading: "
						+ ioe.getMessage());
				this.server.remove(this.ID);
				stop();
			}
	}

	public void open() throws IOException {
		this.streamIn = new DataInputStream(new BufferedInputStream(
				this.socket.getInputStream()));
		this.streamOut = new DataOutputStream(new BufferedOutputStream(
				this.socket.getOutputStream()));
	}

	public void close() throws IOException {
		if (this.socket != null)
			this.socket.close();
		if (this.streamIn != null)
			this.streamIn.close();
		if (this.streamOut != null)
			this.streamOut.close();
	}
}